<template>
  <div class="container">
    <van-popup v-model="show" position="bottom" :style="{ height: '40%' }">
      <van-area
        :area-list="arryReceiveList"
        :value="area"
        class="arryReceiveList"
        @confirm="receiveconfirm"
        @cancel="receivecancel"
        @change="changeArea"
        :columns-num="3"
      />
    </van-popup>

    <van-nav-bar title="经停地址" fixed @click-left="onClickLeft">
      <van-icon name="arrow-left" slot="left" color="#333" size="0.6rem" />
    </van-nav-bar>
    <div class="userinfo">
      <input type="text" placeholder="姓名" v-model="username" />
      <input class="phone" type="text" maxlength="11" placeholder="电话" v-model="userphone" />
    </div>
    <div class="city" @click="city">
      <dl>
        <dt
          :style="receiveAddress.trim() == '' ? '#999999':'color:#000'"
        >{{receiveAddress.trim() == '' ? '请选择省市区' : receiveAddress}}</dt>
        <dd>
          <img src="@/assets/img/WechatIMG2.png" alt />
        </dd>
      </dl>
    </div>
    <div class="address">
      <input type="text" placeholder="详细信息" @click="addressClick" v-model="melinaddress" />
    </div>
    <div class="listOrder">
      <span @click="onRemove">清空当前信息</span>
    </div>
    <div class="box_added">
      <p class="tit">历史地址</p>
      <van-empty description="暂无数据" v-if="!shuerArr.length" />
      <ul v-if="shuerArr" class="uls">
        <dl
          v-for="(item,index) in shuerArr"
          :key="index"
          @click="dlClick(index)"
        >
          <dt>
            <span>{{item.KaUabLinker}}</span>
            <span style="marginLeft: 10px">{{item.KaUabTel}}</span>
          </dt>
          <dd>
            <p>{{`${item.CITYNAME} ${item.AREANAME} ${item.KaUabDes} `}}</p>
          </dd>
        </dl>
      </ul>
    </div>
    <div class="buton">
      <van-button class="butonT" type="primary" size="large" @click="onOK">确定</van-button>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import AreaList from "@/utils/area.js";
import {
  cities,
  areas,
  getKaUserAddressBook,
  operationadress
} from "@/api/add";
import { Area, Empty, Dialog, Toast } from "vant";
Vue.use(Area);
Vue.use(Empty);
Vue.use(Dialog);
Vue.use(Toast);
export default {
  data() {
    return {
      checkArr: [],
      show: false,
      areaList: [],
      shuerArr: [],
      username: "",
      userphone: "",
      arryReceiveList: JSON.parse(JSON.stringify(AreaList)),
      melinaddress: "",
      data: {
        modifyRemark: ""
      },
      receiveAddress: "",
      province: "110000000000",
      cityS: "110100000000",
      area: "110101000000",
      ind: null,
      receive: [],
      cneeLongitude:"",
      cneeLatitude: "",
      stopOverAddress: []
    };
  },
  created() {
    // if (JSON.parse(window.sessionStorage.getItem("receiving"))) {
    //   let rece = JSON.parse(window.sessionStorage.getItem("receiving"));
    //   this.username = rece.KaUabLinker;
    //   this.userphone = rece.KaUabTel;
    //   this.receive[0] = { name: rece.PROVINCENAME, code: rece.KaUabProvince };
    //   this.receive[1] = { name: rece.CITYNAME, code: rece.KaUabCity };
    //   this.receive[2] = { name: rece.AREANAME, code: rece.KaUabArea };
    //   this.receiveAddress = `${rece.PROVINCENAME} ${rece.CITYNAME} ${rece.AREANAME}`;
    //   this.melinaddress = rece.KaUabDes;
    //   this.checkArr =
    //     JSON.parse(window.sessionStorage.getItem("receiving_checkArr")) || [];
    //   this.area = JSON.parse(
    //     window.sessionStorage.getItem("receiving")
    //   ).KaUabArea;
    //   this.province = JSON.parse(
    //     window.sessionStorage.getItem("receiving")
    //   ).KaUabProvince;
    //   this.cityS = JSON.parse(
    //     window.sessionStorage.getItem("receiving")
    //   ).KaUabCity;
    // }
    // if (JSON.parse(sessionStorage.getItem("receivingClick"))) {
    //   let receivingClick = JSON.parse(sessionStorage.getItem("receivingClick"));
    //     this.username = receivingClick.KaUabLinker;
    //     this.userphone = receivingClick.KaUabTel;
    //     if(receivingClick.PROVINCENAME && receivingClick.CITYNAME && receivingClick.AREANAME) {
    //       this.receive[0] = receivingClick.PROVINCENAME ? {name: receivingClick.PROVINCENAME,code: receivingClick.KaUabProvince} : {};
    //       this.receive[1] = receivingClick.CITYNAME ? {name: receivingClick.CITYNAME,code: receivingClick.KaUabCity} : {};
    //       this.receive[2] = receivingClick.AREANAME ? {name: receivingClick.AREANAME,code: receivingClick.KaUabArea} : {}; 
    //     }
    //     this.receiveAddress = `${receivingClick.PROVINCENAME} ${receivingClick.CITYNAME} ${receivingClick.AREANAME}`;
    //     this.area = receivingClick.KaUabArea != '' ? receivingClick.KaUabArea : '110101000000';
    //     this.cityS = receivingClick.KaUabCity != '' ? receivingClick.KaUabCity : '110100000000';
    //     this.province = receivingClick.KaUabProvince != '' ? receivingClick.KaUabProvince : '110000000000';
    //     this.timerStart = receivingClick.KaAppointmentStart;
    //     this.timerEnd = receivingClick.KaAppointmentEnd;
    //     this.cneeLongitude = receivingClick.cneeLongitude;
    //     this.cneeLatitude = receivingClick.cneeLatitude;
    //     this.melinaddress = receivingClick.KaUabDes;
    // }
    // if (JSON.parse(window.sessionStorage.getItem("SAddress"))) {
    //   let Saddress = JSON.parse(window.sessionStorage.getItem("SAddress"));
    //   this.melinaddress = Saddress.address;
    //   this.cneeLongitude = Saddress.longitude;
    //   this.cneeLatitude = Saddress.latitude;
    //   this.province = Saddress.pcode;
    //   this.cityS = Saddress.citycode;
    //   this.area = Saddress.adcode;
    //   this.receive[0] = { name: Saddress.pname, code: Saddress.pcode };
    //   this.receive[1] = { name: Saddress.cityname, code: Saddress.citycode };
    //   this.receive[2] = { name: Saddress.adname, code: Saddress.adcode };
    //   this.receiveAddress = `${Saddress.pname} ${Saddress.cityname} ${Saddress.adname}`;
    // } else if (window.sessionStorage.getItem("SAddressVal")) {
    //   this.melinaddress = window.sessionStorage.getItem("SAddressVal");
    //   this.cneeLongitude = "";
    //   this.cneeLatitude = "";
    // }
    // 回显历史地址
    getKaUserAddressBook({
      addressType: 2,
      searchTxt: "",
      userId: this.$router.history.current.query.kauserId
    }).then(res => {
      this.shuerArr = res.data;
    });
    if (
      JSON.parse(
        sessionStorage.getItem("feed") &&
          JSON.parse(sessionStorage.getItem("feed")).TabArr[0] == "精拼报价"
      )
    ) {
      if (!this.checkArr.filter(item => item == "需要送货").length) {
        this.checkArr.push("需要送货");
      }
    }
  },
  mounted(){
    this.stopOverAddress = JSON.parse(sessionStorage.getItem('stopOverList'))
    if(JSON.parse(sessionStorage.getItem('stopListClick'))){
      let newarr = JSON.parse(sessionStorage.getItem('stopListClick'));
      this.username = newarr.shrpPeopleName;
      this.userphone = newarr.shrpPeopleTel;
      if(newarr.shrpProvinceCode){
         this.province = newarr.shrpProvinceCode
        this.cityS = newarr.shrpCityCode
        this.area = newarr.shrpAreaCode
        this.receive[0] = { name: newarr.shrpProvinceName, code: newarr.shrpProvinceCode };
        this.receive[1] = { name: newarr.shrpCityName, code: newarr.shrpCityCode };
        this.receive[2] = { name: newarr.shrpAreaName, code: newarr.shrpAreaCode };
        this.receiveAddress = `${newarr.shrpProvinceName} ${newarr.shrpCityName} ${newarr.shrpAreaName}`
      }
      this.melinaddress = newarr.shrpDes
    }else{
      let inds = this.$router.history.current.query.ind
      this.username = this.stopOverAddress[inds].shrpPeopleName;
      this.userphone = this.stopOverAddress[inds].shrpPeopleTel;
      if(this.stopOverAddress[inds].shrpProvinceCode && this.stopOverAddress[inds].shrpCityCode && this.stopOverAddress[inds].shrpAreaCode){
        this.province = this.stopOverAddress[inds].shrpProvinceCode
        this.cityS = this.stopOverAddress[inds].shrpCityCode
        this.area = this.stopOverAddress[inds].shrpAreaCode
        this.receive[0] = { name: this.stopOverAddress[inds].shrpProvinceName, code: this.stopOverAddress[inds].shrpProvinceCode };
        this.receive[1] = { name: this.stopOverAddress[inds].shrpCityName, code: this.stopOverAddress[inds].shrpCityCode };
        this.receive[2] = { name: this.stopOverAddress[inds].shrpAreaName, code: this.stopOverAddress[inds].shrpAreaCode };
        this.receiveAddress = `${this.stopOverAddress[inds].shrpProvinceName} ${this.stopOverAddress[inds].shrpCityName} ${this.stopOverAddress[inds].shrpAreaName}`
      }
        this.melinaddress = this.stopOverAddress[inds].shrpDes
    }
  },
  methods: {
    onRemove() {
      this.cityS = "";
      this.area = "";
      this.province = "";
      this.ind = null;
      this.checkArr = [];
      this.userphone = "";
      this.username = "";
      this.melinaddress = "";
      this.receiveAddress = "";
      this.receive = []
    },
    onClickLeft() {
      this.$router.back();
    },
    dlClick(ind) {
      this.ind = ind;
      Dialog.confirm({
        title: "确认提示",
        message: "您确定使用此地址吗？"
      })
        .then(() => {
          this.cneeLongitude = this.shuerArr[ind].longitude
          this.cneeLatitude = this.shuerArr[ind].latitude
          this.shuerArr[ind].cneeLongitude = this.shuerArr[ind].longitude
          this.shuerArr[ind].cneeLatitude = this.shuerArr[ind].latitude
          this.username = this.shuerArr[ind].KaUabLinker
          this.userphone = this.shuerArr[ind].KaUabTel
          this.province = this.shuerArr[ind].KaUabProvince
          this.cityS = this.shuerArr[ind].KaUabCity
          this.area = this.shuerArr[ind].KaUabArea
          this.receiveAddress = `${this.shuerArr[ind].PROVINCENAME} ${this.shuerArr[ind].CITYNAME} ${this.shuerArr[ind].AREANAME}`
          this.melinaddress = this.shuerArr[ind].KaUabDes
          this.receive[0] = { name: this.shuerArr[ind].PROVINCENAME, code: this.shuerArr[ind].KaUabProvince };
          this.receive[1] = { name: this.shuerArr[ind].CITYNAME, code: this.shuerArr[ind].KaUabCity };
          this.receive[2] = { name: this.shuerArr[ind].AREANAME, code: this.shuerArr[ind].KaUabArea };
          // window.sessionStorage.setItem(
          //   "receiving",
          //   JSON.stringify(this.shuerArr[ind])
          // );
          // window.sessionStorage.setItem(
          //   "receiving_checkArr",
          //   JSON.stringify(this.checkArr)
          // );
          // if (this.$router.history.current.query.state == 1) {
          //   this.$router.push({
          //     path: "/details",
          //     query: { orderId: this.$router.history.current.query.orderId }
          //   });
          // } else {
          //   this.$router.push({
          //     path: "/addList",
          //     query: this.$router.history.current.query
          //   });
          // }
        })
        .catch(() => {
          this.ind = null;
        });
    },
    onclick(val) {
      let Arr = this.checkArr.filter(item => item == val);
      if (!Arr.length) {
        this.checkArr.push(val);
      } else {
        this.checkArr.forEach((item, i) => {
          if (item == val) {
            if (
              JSON.parse(
                sessionStorage.getItem("feed") &&
                  JSON.parse(sessionStorage.getItem("feed")).TabArr[0] ==
                    "精拼报价" &&
                  val == "需要送货"
              )
            ) {
            } else {
              this.checkArr.splice(i, 1);
            }
          }
        });
      }
      console.log(this.checkArr);
    },
    city() {
      this.show = !this.show;
    },
    onOK() {
      // if (this.username == "") {
      //   Toast("姓名不能为空");
      // } else if (this.userphone == "") {
      //   Toast("手机号不能为空");
      // } else if (this.receiveAddress == "") {
      //   Toast("请选择省市区");
      // } else if (this.melinaddress == "") {
      //   Toast("请将详细地址补充完整");
      // } else {
          this.stopOverAddress = JSON.parse(sessionStorage.getItem('stopOverList'))
          this.stopOverAddress[this.$router.history.current.query.ind].shrpPeopleName = this.username
          this.stopOverAddress[this.$router.history.current.query.ind].shrpPeopleTel = this.userphone
          this.stopOverAddress[this.$router.history.current.query.ind].shrpProvinceCode = this.province
          this.stopOverAddress[this.$router.history.current.query.ind].shrpProvinceName = this.receive[0].name
          this.stopOverAddress[this.$router.history.current.query.ind].shrpCityCode = this.cityS
          this.stopOverAddress[this.$router.history.current.query.ind].shrpCityName = this.receive[1].name
          this.stopOverAddress[this.$router.history.current.query.ind].shrpAreaCode = this.area
          this.stopOverAddress[this.$router.history.current.query.ind].shrpAreaName = this.receive[2].name
           this.stopOverAddress[this.$router.history.current.query.ind].shrpDes = this.melinaddress
          sessionStorage.setItem('stopOverList',JSON.stringify(this.stopOverAddress))
          sessionStorage.removeItem('stopListClick')
          this.$router.back();
        // let formdata = new FormData();
        // formdata.append("KaUabLinker", this.username);
        // formdata.append("KaUabTel", this.userphone);
        // formdata.append("KaUabType", 2);
        // formdata.append(
        //   "KaUserId",
        //   this.$router.history.current.query.kauserId
        // );
        // formdata.append("KaUabDes", this.melinaddress);
        // formdata.append("KaUabProvince", this.province);
        // formdata.append("KaUabCity", this.cityS);
        // formdata.append("KaUabArea", this.area);
        // formdata.append("KaUabStatus", 1);
        // formdata.append("longitude",this.cneeLongitude);
        // formdata.append("latitude",this.cneeLatitude);
        // operationadress(formdata).then(res => {
        //   this.setVal()
        //   if (this.$router.history.current.query.state == 1) {
        //     this.$router.push({
        //       path: "/details",
        //       query: { orderId: this.$router.history.current.query.orderId }
        //     });
        //   } else {
        //     this.$router.push({
        //       path: "/addList",
        //       query: this.$router.history.current.query
        //     });
        //   }
        // });
      // }
    },
    // setVal(){
    //   window.sessionStorage.setItem(
    //         "receiving",
    //         JSON.stringify({
    //           KaUabLinker: this.username,
    //           KaUabTel: this.userphone,
    //           KaUabType: 2,
    //           KaUserId: this.$router.history.current.query.kauserId,
    //           KaUabDes: this.melinaddress,
    //           PROVINCENAME: this.receive.length
    //             ? this.receive[0].name
    //             : JSON.parse(window.sessionStorage.getItem("receiving"))
    //                 .PROVINCENAME,
    //           CITYNAME: this.receive.length
    //             ? this.receive[1].name
    //             : JSON.parse(window.sessionStorage.getItem("receiving"))
    //                 .CITYNAME,
    //           AREANAME: this.receive.length
    //             ? this.receive[2].name
    //             : JSON.parse(window.sessionStorage.getItem("receiving"))
    //                 .AREANAME,
    //           KaUabArea: this.area,
    //           KaUabCity: this.cityS,
    //           KaUabProvince: this.province,
    //           KaUabStatus: 1,
    //           cneeLongitude: this.cneeLongitude,
    //           cneeLatitude: this.cneeLatitude
    //         })
    //       );
    //       window.sessionStorage.setItem(
    //         "receiving_checkArr",
    //         JSON.stringify(this.checkArr)
    //       );
    // },
    receiveconfirm(val) {
      this.show = false;
      this.receive = val;
      this.data.cneeProvinceCode = this.receive[0].code;
      this.data.cneeCityCode = this.receive[1].code;
      this.data.cneeAreaCode = this.receive[2].code;
      this.receiveAddress = `${this.receive[0].name} ${this.receive[1].name} ${this.receive[2].name}`;
      console.log(this.receiveAddress);
    },
    btntxt() {
      this.show = false;
    },
    receivecancel() {
      this.arryReceiveList = JSON.parse(JSON.stringify(AreaList));
      this.show = false;
    },
    changeArea(picker, index, value) {
      console.log(picker);
      console.log(index);
      console.log(value);
      this.province = index[0].code;
      this.cityS = index[1].code;
      this.area = index[2].code;
      // console.log(item);
      if (value == 0) {
        this.getcities(index[0].code);
      } else if (value == 1) {
        this.getareas(index[1].code);
      }
    },
    getcities(code) {
      cities(code).then(res => {
        let that = this;

        // debugger;
        let cityList = that[that.selectedAddItem].city_list;

        //将获取到的城市 格式化成{110000000000:北京}的格式
        if (res.code == 200) {
          cityList = {};
          res.data.forEach(item => {
            cityList[item.AreaId] = item.AreaName;
          });
          that.getareas(res.data[0].AreaId);
        }

        that[that.selectedAddItem]["city_list"] = cityList;
      });
    },
    addressClick() {
      console.log(this.melinaddress)
      // window.sessionStorage.setItem(
      //   "receivingClick",
      //   JSON.stringify({
      //     KaUabLinker: this.username,
      //     KaUabTel: this.userphone,
      //     PROVINCENAME: this.receive.length ? this.receive[0].name : "",
      //     CITYNAME: this.receive.length ? this.receive[1].name : "",
      //     AREANAME: this.receive.length ? this.receive[2].name : "",
      //     KaUabArea: this.area,
      //     KaUabCity: this.cityS,
      //     KaUabProvince: this.province,
      //     KaUabDes:this.melinaddress,
      //     KaAppointmentStart: this.timerStart,
      //     KaAppointmentEnd: this.timerEnd,
      //     cneeLongitude: this.cneeLongitude,
      //     cneeLatitude: this.cneeLatitude
      //   })
      // );
      // window.sessionStorage.setItem(
      //   "receiving_checkArr",
      //   JSON.stringify(this.checkArr)
      // );
      sessionStorage.setItem('stopListClick',JSON.stringify({
        shrpPeopleName: this.username,
        shrpPeopleTel: this.userphone,
        shrpProvinceCode: this.province,
        shrpProvinceName: this.receive.length ? this.receive[0].name : "",
        shrpCityCode: this.cityS,
        shrpCityName: this.receive[1] ? this.receive[1].name : "",
        shrpAreaCode: this.area,
        shrpAreaName: this.receive[2] ? this.receive[2].name : "",
        shrpDes: this.melinaddress

      }))
      let obj = this.$router.history.current.query;
      obj.flag = 3;
      this.$router.push({
        path: "/inputAddress",
        query: obj
      });
    },
    getareas(code) {
      areas(code).then(res => {
        let that = this;

        let countyList = that[that.selectedAddItem].county_list;

        //将获取到的城市 格式化成{110000000000:北京}的格式
        if (res.code == 200) {
          countyList = {};
          res.data.forEach(item => {
            countyList[item.AreaId] = item.AreaName;
          });
        }

        that[that.selectedAddItem]["county_list"] = countyList;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  position: fixed;
  padding: 56px 0 67px 0;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  font-size: 16px;
  overflow: scroll;
  .userinfo {
    font-size: 13px;
    display: flex;
    border-bottom: 0.5px solid #e5e5e5;
    input {
      padding: 15px 15px;
      box-sizing: border-box;
      border: 0;
      width: 50%;
    }
    // .phone {
    //   text-align: right;
    // }
  }
  .city {
    font-size: 13px;
    padding: 15px 15px;
    box-sizing: border-box;
    background: #fff;
    border-bottom: 0.5px solid #e5e5e5;
    color: #999999;
    dl {
      display: flex;
      justify-content: space-between;
      align-items: center;
      dd {
        img {
          width: 15px;
          height: 20px;
        }
      }
    }
  }
  .address {
    font-size: 13px;
    display: flex;
    // border-bottom: 0.5px solid #e5e5e5;
    input {
      padding: 15px 15px;
      box-sizing: border-box;
      border: 0;
      width: 100%;
    }
  }
  .listOrder {
    color: #f18d00;
    font-size: 14px;
    padding: 10px 15px;
    box-sizing: border-box;
    text-align: right;
    background: #fff;
  }
  .box_added {
    padding: 10px;
    box-sizing: border-box;
    background: #fff;
    margin-top: 10px;
    .uls {
      // height: 190px;
      width: 100%;
      // overflow-y: scroll;
      padding: 5px;
      box-sizing: border-box;
    }
    ul {
      font-size: 15px;
      dl {
        overflow-y: hidden;
        padding: 15px 18px;
        box-sizing: border-box;
        border-top: 1px solid #efefef;
      }
      .active {
        border: 0.5px solid #f18d00;
        color: #f18d00;
        background: #fffaf2;
      }
    }
    .tit {
      padding-bottom: 5px;
      box-sizing: border-box;
      line-height: 32px;
    }
    .checkSteper {
      padding-bottom: 5px;
      box-sizing: border-box;
      font-size: 15px;
      background: #fff;
      box-sizing: border-box;
      ul {
        // width: 100%;
        // height: 500px;
        // overflow-y: scroll;
        dl {
          overflow: hidden;
        }
        display: flex;
        li {
          border: 1px solid #f3f3f3;
          color: #666666;
          width: 100px;
          height: 30px;
          text-align: center;
          line-height: 30px;
          margin-right: 18px;
          background: #f3f3f3;
          border-radius: 4px;
        }
        .active {
          border: 0.5px solid #f18d00;
          color: #f18d00;
          background: #fffaf2;
        }
      }
    }
  }
  .buton {
    padding: 8px 15px;
    box-sizing: border-box;
    display: flex;
    border-radius: 5px;
    justify-content: space-around;
    background: #fff;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    .butonT {
      background: #f18d00;
      width: 100%;
      // width: 328px;
      height: 44px;
      border: 1px solid #f18d00;
    }
  }
  .shell {
    background: #ffffff;
    border: 0.5px solid #f18d00;
    border-radius: 4px;
    color: #666666;
  }
}
/deep/.van-picker-column__wrapper li{
  height:44PX;/*no*/
}
</style>